<?php
namespace app\realname\controller;

use tp5_lib\api\controller\ApiBaseController;
use tp5_lib\realname\model\IDCardModel;
use think\File;

class ApiController extends ApiBaseController
{
    public function upload()
    {
        $user=$this->checkLogin();
        $data=input();
        $data["user_id"]=$user["id"];
        $data["time"]=time();
        unset($data["token"]);

        $model=new IDCardModel();
        if(!$model->check($data["no"])){
            $this->error("请输入正确的身份证号");
        }

        $upload_dir=env("root_path").'/public/uploads';
        if(!file_exists($upload_dir)){
            mkdir($upload_dir);
        }
        $upload_dir.="/id_card";
        if(!file_exists($upload_dir)){
            mkdir($upload_dir);
        }
        $path="uploads/id_card/";
        $save_name=$user["id"]."-".time()."-";
        
        /** @var File[] $files */
        $files = $this->request->file();
        if(isset($files["frontage"])){
            if($info=$files["frontage"]->move($upload_dir, $save_name."frontage")){
                $data["frontage"]=$path . $info->getSaveName();
            }
            else{
                $this->error($files["frontage"]->getError());
            }
        }
        if(isset($files["backside"])){
            if($info=$files["backside"]->move($upload_dir, $save_name."backside")){
                $data["backside"]=$path . $info->getSaveName();
            }
            else{
                $this->error($files["backside"]->getError());
            }
        }

        if(!$model->db()->insert($data)){
            $this->error("保存失败");
        }
        $this->success();
    }
    public function getRecord()
    {
        $user=$this->checkLogin();
        $model=new IDCardModel();
        if($record=$model->db()->where("user_id",$user["id"])->where("status",1)->find()){
            $this->result($record,1);
        }
        if($record=$model->db()->where("user_id",$user["id"])->order("time desc")->find()){
            $this->result($record,-1);
        }
    }
}
